window.onload = function () {
    function request(obj) {
        // 限制各个数据
        // 请求路径
        if (obj.url === undefined) {
            throw new Error('请求路径不能为空！')
        }
        // 判断类型
        if (typeof obj.url != 'string') {
            throw new Error('请求路径错误！')
        }
        // dataType
        if (obj.dataType === undefined) {
            obj.dataType = 'json'
        }
        // 请求方式 - get/put/delete/post都可以，大小写都可以，可以不传，默认get
        if (obj.method === undefined) { // 如果没有传递
            // 给默认值get
            obj.method = 'get'
        }
        // 说明get传递了 - 限制是否是这4种方式
        if (obj.method.toLowerCase() != 'get' && obj.method.toLowerCase() != 'post' && obj.method.toLowerCase() != 'put' && obj.method.toLowerCase() != 'delete') {
            // 抛出自定义错误
            throw new Error('请求方式不正确！')
        }
        // async
        if (obj.async === undefined) {
            obj.async = true
        }
        if (typeof obj.async != 'boolean') {
            throw new Error('同步false异步true！')
        }
        // success
        if (obj.success === undefined) {
            obj.success = () => { }
        }
        if (typeof obj.success != 'function') {
            throw new Error('success是函数！')
        }
        // error
        if (obj.error === undefined) {
            obj.error = () => { }
        }
        if (typeof obj.error != 'function') {
            throw new Error('error是函数！')
        }
        // data - 可以是查询字符串，方便传递的话个，给对象更好
        // ajax语法中要求必须是查询字符串 - 如果是对象，需要转成查询字符串
        let data
        if (obj.data != undefined) {
            if (Object.prototype.toString.call(obj.data) === '[object Object]') {
                // 对象 - 转字符串
                let arr = []
                for (let key in obj.data) {
                    arr.push(key + '=' + obj.data[key])
                }
                data = arr.join('&')
            } else if (Object.prototype.toString.call(obj.data) === '[object String]') {
                // 字符串
                data = obj.data
            } else {
                throw new Error('data是字符串或对象！')
            }
            // 判断请求方式是否是get
            if (obj.method.toLowerCase() === 'get') {
                obj.url += '?' + data
            }
        }
        var xhr = new XMLHttpRequest;
        xhr.open(obj.method, obj.url, obj.async);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let res
                    switch (obj.dataType) {
                        case 'xml':
                            res = xhr.responseXML
                            break
                        case 'json':
                            res = xhr.responseText
                            res = JSON.parse(res)
                            break
                        case 'text':
                            res = xhr.responseText
                            break
                        default:
                            throw new Error('dataType必须是json/text/xml！')
                    }
                    obj.success(res)
                } else {
                    obj.error('错误')
                }
            }
        }
        if (obj.method.toLowerCase() === 'post' && data) {
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(data)
            return
        }
        xhr.send()
    }
    function setCookie(key, value, seconds, path = '/') {
        let date = new Date()
        date.setTime(date.getTime() - 8 * 3600 * 1000 + seconds * 1000)
        document.cookie = `${key}=${value};expires=${date};path=${path}`
    }
    function getCookie(key) {
        let cookies = document.cookie
        if(!cookies) {
            return
        }
        let cookiesArr = cookies.split('; ')
        for(let a = 0; a < cookiesArr.length; a++) {
            let brr = cookiesArr[a].split('=')
            if(brr[0] === key) {
                return brr[1]
            }
        }
    }

    var form = document.querySelector('form')
    var username = document.querySelector('[name="username"]')
    var password = document.querySelector('[name="password"]')
    form.onsubmit = function () {
        console.log(123);
        request({
            method: 'post',
            url: '/front/api/user/login',
            data: {
                username: username.value,
                password: password.value,
            },
            success(res) {

                let { error_code, msg } = res
                console.log(error_code);
                if (error_code === 200) {
                    setCookie('username', res.data.username, 7200)
                    //提示登录成功
                    popup.msg(msg, () => {
                        location.href = '/'
                    })

                } else {
                    popup.msg(msg)
                }
            }
        })

        return false
    }
}